package ui.search

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.rememberWindowState
import model.enums.NetworkSate
import model.repository.UserRepository
import model.vo.SearchedItem
import state.ApplicationWindowsState
import theme.EasyChatTheme
import ui.compose.NetworkImage
import ui.compose.RectIconButton


/**
 * @author wei kunJie
 * @date 2024/4/13 14:04:20
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SearchWindows(
    easyChatTheme: MutableState<EasyChatTheme>,
    applicationWindowsState: ApplicationWindowsState,
    close: () -> Unit
) = Window(
    icon = painterResource("icon/ic_logo.svg"),
    transparent = true,//设置为透明窗口
    undecorated = true, //透明窗口必须取消装饰，这样就没默认的窗口标题栏和那些最小化、最大化、关闭什么的了
    onCloseRequest = close,
    title = "全网搜索",
    state = rememberWindowState(width = 690.dp, height = 750.dp, position = WindowPosition(Alignment.Center))
) {
    //rememberCoroutineScope() 是一个用于在 Composable 函数中创建协程作用域
    val coroutineScope = rememberCoroutineScope()
    //创建ViewModel
    val viewModel = remember { SearchViewModel(applicationWindowsState, coroutineScope) }
    val windowsCorner = 3.dp//窗口圆角大小
    //窗口表面，用来定窗口样式
    Surface(
        modifier = Modifier.fillMaxSize()
            .padding(5.dp)
            .shadow(3.dp, RoundedCornerShape(windowsCorner + 3.dp)),//窗口阴影样式
        color = easyChatTheme.value.mainWhite,
        shape = RoundedCornerShape(windowsCorner) //窗口圆角
    ) {
        Column {
            Row(
                modifier = Modifier.padding(top = 45.dp).fillMaxWidth()
            ) {
                // 焦点
                val hasFocus = remember { mutableStateOf(false) }
                Row(
                    modifier = Modifier.padding(horizontal = 15.dp).onFocusChanged {
                        hasFocus.value = it.hasFocus
                    }
                )
                {
                    BasicTextField(
                        value = viewModel.searchText.value,
                        onValueChange = {
                            viewModel.searchText.value = it
                        },
                        modifier = Modifier
                            .background(
                                color = Color(0X11363636),
                                shape = RoundedCornerShape(4.dp)
                            )
                            .height(30.dp)
                            .weight(1f)
                            .border(
                                border = if (hasFocus.value)
                                    BorderStroke(0.8.dp, easyChatTheme.value.mainColor)
                                else BorderStroke(0.dp, Color.Transparent),
                                shape = RoundedCornerShape(4.dp)
                            ),
                        singleLine = true,
                        cursorBrush = SolidColor(easyChatTheme.value.mainColor),//游标颜色
                        decorationBox = @Composable { innerTextField ->
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.padding(start = 8.dp)
                            ) {
                                //左边的放大镜图标
                                Icon(
                                    painter = painterResource("icon/ic_search.svg"),
                                    contentDescription = "搜索",
                                    tint = Color(0XFF696969),
                                    modifier = Modifier.size(18.dp)
                                )
                                //输入框
                                Box(
                                    modifier = Modifier.weight(1f).fillMaxHeight().padding(horizontal = 3.dp),
                                    contentAlignment = Alignment.CenterStart
                                ) {
                                    innerTextField()//输入区
                                    //hint
                                    if (viewModel.searchText.value.isEmpty()) {
                                        Text(
                                            text = "输入搜索关键字", style = TextStyle(
                                                fontSize = 12.sp,
                                                color = Color(0XEE696969)
                                            )
                                        )
                                    }
                                }
                            }
                        }
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    //搜索按钮
                    Button(
                        enabled = viewModel.searchBtnEnabled.value,
                        onClick = {
                            //点击搜索
                            viewModel.searchChannelMapping()
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = easyChatTheme.value.mainColor,
                        ),
                        shape = RoundedCornerShape(5.dp),
                        modifier = Modifier.height(30.dp).width(60.dp)
                    ) {
                        Text(text = "搜索", style = TextStyle(color = Color.White, fontSize = 12.sp))
                    }
                }
            }
            LazyColumn(modifier = Modifier.padding(20.dp)) {
                items(viewModel.searchedItems) { item ->
                    SearchedRow(easyChatTheme=easyChatTheme,item = item, viewModel = viewModel)
                    Spacer(modifier = Modifier.height(12.dp))
                }
            }
        }
    }
    //窗口可拖动区域，鼠标按住后可以拖动窗口
    WindowDraggableArea {
        Surface(
            modifier = Modifier.fillMaxWidth().height(Dp(45f))
                .padding(5.dp),
            color = Color.Transparent,
            shape = RoundedCornerShape(windowsCorner, windowsCorner)
        ) {
            val isMouseIn = remember { mutableStateOf(false) }
            Row(verticalAlignment = Alignment.CenterVertically) {
                Spacer(Modifier.size(33.dp))
                Text(text = "全网搜索", textAlign = TextAlign.Center, modifier = Modifier.weight(1f))
                RectIconButton(
                    onClick = close,
                    modifier = Modifier.size(33.dp).background(
                        color = if (isMouseIn.value) Color(0xFFC42B1C)
                        else Color.Transparent
                    ).onPointerEvent(PointerEventType.Enter) { isMouseIn.value = true }
                        .onPointerEvent(PointerEventType.Exit) { isMouseIn.value = false },
                ) {
                    Icon(
                        painter = painterResource("icon/ic_close.svg"),
                        contentDescription = "关闭",
                        tint = if (isMouseIn.value) Color.White else Color.Black,
                        modifier = Modifier.size(33.dp).padding(9.dp)
                    )
                }
            }
        }
    }

    if (viewModel.networkState.value != NetworkSate.watting) {
        //网络请求状态的提示对话框，如失败提示
        AlertDialog(
            onDismissRequest = {
                viewModel.networkState.value = NetworkSate.watting
            },
            title = {
                Text(
                    text = viewModel.networkRMsg.value,
                    fontWeight = FontWeight.W400,
                    style = TextStyle(
                        textAlign = TextAlign.Center,
                        fontSize = 16.sp,
                        color = Color.Black
                    )
                )
            },
            buttons = {
                Row(
                    modifier = Modifier.padding(all = 10.dp).width(200.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Button(
                        modifier = Modifier.fillMaxWidth(),
                        onClick = { viewModel.networkState.value = NetworkSate.watting },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = easyChatTheme.value.mainColor,
                        )
                    ) {
                        Text(text = "我知道了", color = Color.White)
                    }
                }
            }
        )
    }
}

@Composable
fun SearchedRow(easyChatTheme: MutableState<EasyChatTheme>,item: SearchedItem, viewModel: SearchViewModel) {

    val flag = remember { mutableStateOf(false) }
    Row(verticalAlignment = Alignment.CenterVertically) {
        //头像
        NetworkImage(
            url = item.headImage,
            painterFor = { remember { BitmapPainter(it) } },
            contentDescription = "头像",
            modifier = Modifier.size(51.dp).clip(CircleShape),
            contentScale = ContentScale.Crop,
            defaultPainterFor = painterResource("image/default_head.png")
        )
        Spacer(modifier = Modifier.width(10.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(text = item.usernameOrGroupName)
            Text(text = item.userAccountOrGroupAccount)
        }
        if (item.isGroup) {
            Text("（群聊）", color = Color(0xFF515151))
        }
        Spacer(modifier = Modifier.width(10.dp))
        Button(
            onClick = {
                //添加
                flag.value = true
                viewModel.addUserAccount.value = item.userAccountOrGroupAccount
            },
            modifier = Modifier.height(35.dp).width(65.dp),
            colors = ButtonDefaults.buttonColors(
                backgroundColor = Color.White,
            ),
            enabled = !viewModel.isFriend(item)
//            border = BorderStroke(1.dp, Color.LightGray),
        ) {
            Text(text = "添加")
        }
    }
    if (flag.value) {
        Dialog(onDismissRequest = { flag.value = false }, content = {
            Column(
                modifier = Modifier
                    .size(350.dp)
                    .background(easyChatTheme.value.mainWhite),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(7.dp))
                Text("好友申请", fontSize = 14.sp)
                Spacer(modifier = Modifier.height(5.dp))
                Spacer(
                    modifier = Modifier.fillMaxWidth().height(1.dp)
                        .background(color = Color(0x22747A80))
                )
                Spacer(modifier = Modifier.height(7.dp))
                Row(Modifier.padding(horizontal = 25.dp)) {
                    //头像
                    NetworkImage(
                        url = item.headImage,
                        painterFor = { remember { BitmapPainter(it) } },
                        contentDescription = "头像",
                        modifier = Modifier.size(51.dp).clip(CircleShape),
                        contentScale = ContentScale.Crop,
                        defaultPainterFor = painterResource("image/default_head.png")
                    )
                    Spacer(modifier = Modifier.width(10.dp))
                    Column(modifier = Modifier.weight(1f)) {
                        Text(text = item.usernameOrGroupName)
                        Text(text = item.userAccountOrGroupAccount)
                    }
                }
                Spacer(modifier = Modifier.height(7.dp))
                Text(
                    text = "填写验证信息",
                    modifier = Modifier.width(300.dp),
                    fontSize = 14.sp,
                    color = Color(0XEE696969)
                )
                Spacer(modifier = Modifier.height(5.dp))
                Box(
                    modifier = Modifier.width(300.dp).height(100.dp).border(BorderStroke(0.2.dp, Color.Black))
                        .background(color = Color.White, shape = RoundedCornerShape(3.dp))
                ) {
                    BasicTextField(
                        value = viewModel.authenticationInformation.value,
                        textStyle = TextStyle(
                            fontSize = 15.sp,
                            color = Color.Black
                        ),
                        onValueChange = { viewModel.authenticationInformation.value = it },
                        modifier = Modifier.fillMaxSize().padding(10.dp)
                    )
                }
                Spacer(modifier = Modifier.weight(1f))
                Row {
                    Button(
                        onClick = {
                            //发送好友申请
                            viewModel.addFriend()
                        },
                        colors = ButtonDefaults.buttonColors(
                            backgroundColor = easyChatTheme.value.mainColor,
                        )
                    ) { Text(text = "发送") }
                    Spacer(modifier = Modifier.width(10.dp))
                    Button(
                        onClick = { flag.value = false }, colors = ButtonDefaults.buttonColors(
                            backgroundColor = Color.White,
                        )
                    ) { Text(text = "取消") }
                }
                Spacer(modifier = Modifier.height(12.dp))
            }
        })
    }
}
